<template>

    <el-form ref="form" :model="form" :rules="$rules.carForm" label-width="120px" @submit.prevent="saveOrUpdate" style="margin:20px;width:80%;min-width:600px;" v-loading="loading">

      <template v-if="isAudit">
        <el-row>
          <el-col :span="12">
              <el-form-item label="审核结果:" prop="status">
                <el-radio v-model="form.status" label="1" border >通过</el-radio>
                <el-radio v-model="form.status" label="2" border >不通过</el-radio>
              </el-form-item>
          </el-col>
        </el-row>

        <el-row  v-if="form.status==2">
          <el-col>
            <el-form-item label="原因:" prop="reason">
                <el-input type="textarea" :rows="5" v-model="form.reason" placeholder="请输入不通过的原因"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="margin-bottom: 12px">
          <el-col :offset="12">
              <el-button type="primary" @click="saveAudit()">保存</el-button>
          </el-col>
        </el-row>
      </template>


      <template>
        <el-row>
          <el-col>
            <el-form-item label="检索发布人:" prop="userId">
            <el-autocomplete
                    v-model="nickName"
                    popper-class="my-autocomplete"
                    :fetch-suggestions="querySearch"
                    :trigger-on-focus="false"
                    placeholder="检索关键词可为学员的身份证、姓名、手机号"
                    @select="handleSelect">
              <i class="el-icon-search el-input__icon"  slot="suffix"> </i>
              <template slot-scope="{ item }">
                <div class="name">{{ item.nickName }}</div>
                <span class="addr">{{ item.mobile }}</span>
              </template>
            </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

    <el-collapse v-model="activeNames">

        <el-collapse-item name="a1">
        <template slot="title">卖车人信息</template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="卖车人姓名:"  prop="sellerName">
              <el-input v-model="form.sellerName" placeholder="请输入卖车人姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卖车人手机号:" prop="sellerMobile" >
              <el-input v-model="form.sellerMobile" placeholder="请输入卖车人手机号" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="看车城市:" prop="cityId">
                <el-select v-model="form.provinceId" placeholder="请选择看车省份" @change="provinceChange()">
                  <el-option v-for="item in provinces" :key="item.id" :label="item.shortName" :value="item.id"></el-option>
                </el-select>
                <el-select v-model="form.cityId" placeholder="请选择看车城市" >
                  <el-option v-for="item in citys" :key="item.id" :label="item.shortName" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="22">
            <el-form-item label="看车地点:" prop="address">
              <el-input v-model="form.address" placeholder="请输入看车地点"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-collapse-item>

      <el-collapse-item name="a1">
        <template slot="title">选择车型</template>
        <el-row>
          <el-col>
            <el-form-item label="车型:" prop="typeId">
              <template v-for="item in truckTypes">
                <el-radio v-model="form.typeId" :label="item.id" border class="truckTypes">{{item.name}}</el-radio>
              </template>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-alert class="tip" title="图片上传大小不限，但不宜过大，并且保证图片清晰" type="success" ></el-alert>
          </el-col>
        </el-row>

        <el-row>
             <el-col :span="3"  v-for="(item,index) in imgs"   :key="item.id">
                  <el-upload v-if="index<7"
                          action="javascript:;"
                          class="avatar-uploader"
                          :show-file-list="true"
                          :http-request="imgUploadFn"
                          :on-remove = "imgRemove"
                          :data="{index:index}"
                          :before-upload="beforeImgUpload">
                    <img v-if="form.imgs[index]&&form.imgs[index].url" :src="form.imgs[index].url" class="avatar"/>
                    <i v-else class="el-icon-plus avatar-uploader-icon" style="color:red;font-size:12px;">{{item.name}}</i>
                  </el-upload>
              </el-col>
          </el-row>

          <el-row>
              <el-col :span="3"  v-for="(item,index) in imgs"   :key="item.id">
                  <el-upload v-if="index>=7&&index<14"
                             action="javascript:;"
                             class="avatar-uploader"
                             :show-file-list="true"
                             :http-request="imgUploadFn"
                             :on-remove = "imgRemove"
                             :data="{index:index}"
                             :before-upload="beforeImgUpload">
                      <img v-if="form.imgs[index]&&form.imgs[index].url" :src="form.imgs[index].url" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon" style="color:red;font-size:12px;">{{item.name}}</i>
                  </el-upload>
              </el-col>
          </el-row>

          <el-row>
              <el-col :span="3"  v-for="(item,index) in imgs"   :key="item.id">
                  <el-upload v-if="index>=14"
                             action="javascript:;"
                             class="avatar-uploader"
                             :show-file-list="true"
                             :http-request="imgUploadFn"
                             :on-remove = "imgRemove"
                             :data="{index:index}"
                             :before-upload="beforeImgUpload">
                      <img v-if="form.imgs[index]&&form.imgs[index].url" :src="form.imgs[index].url" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon" style="color:red;font-size:12px;">{{item.name}}</i>
                  </el-upload>
              </el-col>
          </el-row>

      </el-collapse-item>

        <el-collapse-item name="a2" title="车辆信息">
          <el-row>
            <el-col :span="12">
                <el-form-item label="车辆品牌:" prop="parentBrand">
                  <el-select v-model="form.parentBrand" placeholder="请选择车辆品牌" @change="parentBrandChange()" >
                    <el-option v-for="item in parentBrands" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                  <el-select v-model="form.brandId" placeholder="请选择车辆品牌" >
                    <el-option v-for="item in brandIds" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否可过户:" prop="isTransfer">
                <el-radio v-model="form.isTransfer" label="1" border class="truckTypes">是</el-radio>
                <el-radio v-model="form.isTransfer" label="0" border class="truckTypes">否</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否可提档:" prop="takeRecord">
                <el-radio v-model="form.takeRecord" label="1" border class="truckTypes">是</el-radio>
                <el-radio v-model="form.takeRecord" label="0" border class="truckTypes">否</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
        <el-row>

          <el-col :span="8">
            <el-form-item label="上户日期:" prop="buyDate">
              <el-date-picker  v-model="form.buyDate" type="date" placeholder="请选择上户日期"  value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="排放标准:" prop="outStandard">
              <el-select v-model="form.outStandard" placeholder="请选择排放标准" >
                <el-option v-for="item in outStandards" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="最大马力(匹):" prop="enginePower">
              <el-input v-model="form.enginePower" placeholder="请输入最大马力"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>

          <el-col :span="8">
            <el-form-item label="箱体长度(m):" prop="boxLength">
              <el-input v-model="form.boxLength" placeholder="请填写箱体长度 (单位米)"></el-input>
            </el-form-item>
          </el-col>


          <el-col :span="8">
            <el-form-item label="车辆价格(万元):" prop="sellPrice">
              <el-input v-model="form.sellPrice" placeholder="请填写车辆价格（单位：万元）"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="驱动类型:" prop="driverType">
              <el-select v-model="form.driverType" placeholder="请选择驱动类型" >
                <el-option v-for="item in driverTypes" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>


        <el-row>

          <el-col :span="8">
            <el-form-item label="发动机品牌:" prop="engineId">
              <el-select v-model="form.engineId" placeholder="请选择发动机品牌" >
                <el-option v-for="item in engines" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="燃料类型:" prop="fuelType">
              <el-select v-model="form.fuelType" placeholder="请选择发动机品牌" >
                <el-option v-for="item in fuelTypes" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="8">
            <el-form-item label="表显里程:" prop="mileage">
              <el-input v-model="form.mileage" placeholder="请填写车辆价格（单位：万元）"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>

          <el-col :span="8">
            <el-form-item label="车辆颜色:" prop="color">
              <el-input v-model="form.color" placeholder="请填写车辆颜色"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-form-item label="车辆说明:" prop="info"  >
            <el-input type="textarea" :rows="5" v-model="form.info" placeholder="请输入车辆简介"></el-input>
          </el-form-item>
        </el-row>

      </el-collapse-item>

    </el-collapse>

    <el-row>
      <el-col :offset="8">
        <el-form-item>
          <el-button type="primary" @click="saveOrUpdate()" v-if="!isAudit">保存</el-button>
        </el-form-item>
      </el-col>
    </el-row>

  </el-form>

</template>

<script>
    import axios from "axios";
    export default {
        name:'TruckEditor',
        data() {
            return {
                nickName:'',
                loading:false,
                activeNames:['a0','a1','a2','a3','a4'],
                isAudit:false,
                uploadDisabled:false,
                provinces:[],
                citys:[],
                truckTypes:[],
                parentBrands:[],
                brandIds:[],
                driverTypes:[],
                fuelTypes:[],
                outStandards:[],
                engines:[],
                imgs:[],
                form: {
                    reason:'',
                    status:'2',
                    takeRecord:'0',
                    isTransfer:'0',
                    truckId:0,
                    typeId:null,
                    sellerName:'',
                    sellerMobile:'',
                    provinceId:null,
                    cityId:null,
                    address:'',
                    imgs:new Array(21),
                    parentBrand:null,
                    brandId:null,
                    buyDate:null,
                    outStandard:null,
                    enginePower:null,
                    boxLength:0,
                    sellPrice:0,
                    driverType:null,
                    fuelType:1,
                    mileage:0,
                    color:'',
                    engineId:null,
                    userId:null
                }
            }
        },
        methods: {

            handleSelect(item) {
                this.form.userId = item.userId;
                this.nickName = item.mobile+"/"+item.nickName;
            },
            querySearch(queryString, cb) {
                if(queryString==''){
                    return;
                }
                let params = {word:queryString};
                this.$api.loadSuggestUser(params).then(response=>{
                    let result = response.data;
                    let data = result.data;
                    if(result.code==0){
                        this.suggestStudent = data;
                        cb(this.suggestStudent);
                    }
                });
            },
            //上传课程封面图
            coverUploadFn(d) {
                // this.$api.file(d.file).then(d => {
                //     if (d.data.code !== 0) {
                //         this.$alert(d.data.msg);
                //         return;
                //     }
                //     this.form.coverImgs.push({ url: d.data.data});
                //     this.uploadDisabled  = this.form.coverImgs.length>=1;
                // });
            },
            //上传前判断
            beforeImgUpload(file) {
                if (file.type === "image/png" || file.type === "image/jpeg") {
                    return true;
                }
                this.$message.error("照片只能是JPG或PNG格式!");
                return false;
            },
            //身份证正反面
             imgUploadFn(d) {
                let index = d.data.index;
                let file=d;
                this.$api.file(d.file).then(d => {
                    if (d.data.code !== 0) { this.$message.alert(d.data.msg);return;}
                    this.$set(this.form.imgs, index, {url:d.data.data,uid:file.file.uid});
                });
            },
            imgRemove(file,fileList) {
              this.form.imgs = this.form.imgs.filter(f => f.uid != file.raw.uid);
            },
            provinceChange(){
                  let params = {parentId:this.form.provinceId};
                  this.form.cityId='';
                  this.$api.getRegion(params).then(response=>{
                      let result = response.data;
                      let d = result.data;
                      if(result.code==0){
                          this.citys = d;
                      }
                  });
                },
              parentBrandChange(){
                  this.form.brandId = '';
                  let params = {parentId:this.form.parentBrand};
                  this.$api.getTruckBrand(params).then(response=>{
                      let result = response.data;
                      let d = result.data;
                      if(result.code==0){
                          this.brandIds = d;
                      }
                  });
              },
            saveOrUpdate(){

                this.$refs.form.validate(valid => {
                        if (!valid) {
                          return false;
                        }
                        if(this.form.parentBrand==''||this.form.brandId==''){
                            alert("请先选择品牌");
                            return false;
                        }
                        for(var i=0;i<3;i++){
                            let url =this.form.imgs[i];
                            if(url==null || url.length==0){
                                alert("车辆前三张照片必填！");
                                return false;
                            }
                        }
                        this.loading = true;
                        let params = this.form;
                        params.imgs = this.form.imgs.map(function(v){
                            return v.url;
                        });
                        this.$api.saveTruck(params).then(response => {
                            let result = response.data;
                            if (result.code == 0) {
                                this.$message.success("保存成功！");
                                this.$router.push({name:'TruckList'});
                            } else {
                                this.$message.error(result.msg);
                            }
                            this.loading = false;
                        });
                });
            },
            saveAudit(){
                let params = {truckId:this.form.truckId,status:this.form.status};

                if(this.form.status==2){
                    params.reason = this.form.reason;
                    if(this.form.reason==''){
                        this.$message.alert("审核不通过时,审核不通过的原因必填!");
                        return;
                    }
                }
                this.$api.saveAudit(params).then(response=>{
                    let result = response.data;
                    if(result.code==0){
                        this.$message.success("保存审核结果成功!");
                        this.$router.push({name:'TruckList'});
                    }else{
                        this.$message.error(result.msg);
                    }
                });
            },
            initProvince(){
                //初始化省份
                let params = {parentId:1};
                this.$api.getRegion(params).then(response=>{
                    let result = response.data;
                    let d = result.data;
                    if(result.code==0){
                        this.provinces = d;
                        // this.adminList = data.list;
                    }
                });
            },
            initTruckType(){
                this.$api.getTruckType().then(response=>{
                    let result = response.data;
                    let d = result.data;
                    if(result.code==0){
                        this.truckTypes = d;
                    }
                });
            },
            initParentBrand(){
                this.$api.getTruckBrandParent().then(response=>{
                    let result = response.data;
                    let d = result.data;
                    if(result.code==0){
                        this.parentBrands = d;
                    }
                });
            },
            initEnums(){
                this.$api.getTruckEnums().then(response=>{
                    let result = response.data;
                    let d = result.data;
                    if(result.code==0){
                        this.driverTypes =  d.driverType;
                        this.fuelTypes =  d.fuelType;
                        this.outStandards =  d.outStandard;
                        this.imgs = d.imgs;
                    }
                });
            },
            initEngines(){
                this.$api.getEngines().then(response=>{
                    let result = response.data;
                    let d = result.data;
                    if(result.code==0){
                        this.engines = d;
                    }
                });
            }
        },
        mounted(){   },

        created(){
            let params = this.$route.params;
            this.form.truckId = params.truckId;
            //先判断是否是审核，显示审核的内容版块，并且收起所有的版块
            let operateType =  params.operateType;
            if(operateType=='audit'){
                this.isAudit = true;
                this.activeNames=[];
            }
            let apiQuery = this.$api;
            let that = this;
            this.loading=true;
            axios.all([
                this.initProvince(),
                //车型字典
                this.initTruckType(),
                //车辆品牌
                this.initParentBrand(),
                //初始化truckEnums 常规枚举类型  driverType  fuelType outStandard
                this.initEnums(),
                //初始化发动机品牌
                this.initEngines()
            ]).then(axios.spread(function (userResp, reposResp) {
                that.loading=false;
                if(params&&params.truckId) {
                    that.loading=true;
                    apiQuery.getTruckInfo(params).then(response=>{
                        let result = response.data;
                        let d = result.data
                        if(result.code==0){
                              that.form.sellerName = d.sellerName;
                              that.form.sellerMobile = d.sellerMobile;
                              that.form.provinceId = d.provinceId;
                              that.provinceChange();
                              that.form.cityId = d.cityId;
                              that.form.address  = d.address;
                              that.form.typeId = d.typeId;
                              let imgs = [];
                              d.imgs.forEach(img=>{
                                  imgs.push({url:img,uid:new Date().getTime()});
                              });
                              that.form.imgs = imgs;
                              that.form.parentBrand  = d.parentBrand;
                              that.parentBrandChange();
                              that.form.brandId= d.brandId;
                              that.form.buyDate =d.buyDate;
                              that.form.outStandard = d.outStandard2;
                              that.form.enginePower = d.enginePower;
                              that.form.boxLength = d.boxLength;
                              that.form.sellPrice = d.sellPrice;
                              if(d.driverType){
                                  that.form.driverType = parseInt(d.driverType);
                              }
                              that.form.engineId  = d.engineId;
                              if(d.fuelType){
                                that.form.fuelType = parseInt(d.fuelType);
                              }
                              that.form.mileage = d.mileage;
                              that.form.color = d.color;
                              that.form.info = d.info;
                              if(d.isTransfer){
                                  that.form.isTransfer = d.isTransfer+"";
                              }
                              if(d.takeRecord){
                                  that.form.takeRecord = d.takeRecord+"";
                              }
                              that.form.reason = d.reason;
                              if(d.status){
                                  that.form.status = d.status+"";
                              }
                              that.form.userId = d.userId;
                              that.nickName =d.mobile+"/"+d.nickName;
                        }else{
                            that.$message.error(result.msg);
                        }
                        that.loading=false;
                    });
                }
             }));
        }
    }
</script>
<style lang="less">
  .hiddenUpload .el-upload--picture-card  {
    display: none;
  }
  .el-upload--picture-card{
    width: 100px;
    height:100px;
    line-height:100px;
  }
  .w450{
    width:350px;
    display:inline-block;
  }
  .img-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 178px;
    height: 178px;
    overflow: hidden;
  }
  .img-uploader .img-upload:hover {
    border-color: #409EFF;
  }
  .img-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .outimg {
    width: 178px;
    height: 178px;
    display: block;
    border: 1px dashed #d9d9d9;
    background-position:center;
    background-size:cover;
    -webkit-background-size:cover;
  }
  .el-collapse-item__header{
    color:#04adfc;
    border-left: 5px solid #04adfc;
    padding-left: 18px;
    font-weight: bold;
  }
  .truckTypes{
    margin: 5px 5px 5px 5px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .el-upload--picture-card{
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  .el-upload-list--picture-card .el-upload-list__item{
    width: 100px!important;
    height: 100px!important;
    line-height: 100px!important;
  }
  .el-upload-list__item .el-icon-close{
    display:block;
    color: red;
  }
  .el-upload-list {
    width: 100px;
  }
  .name {
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .addr {
    font-size: 12px;
    color: #b4b4b4;
  }
  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px;

      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }
      .highlighted .addr {
        color: #ddd;
      }
    }
  }
  .el-autocomplete{
    width: 450px;
  }

</style>
